<?php
/**
 * Created by PhpStorm.
 * User: cheng
 * Date: 2017/2/16
 * Time: 13:54
 */
 require_once ('config.php');
 require_once ('json.php');
 class Vote{
     public function voteAccessTicket(){
         //前端传过来的公司id
         $json = new CreateJson();
         $companyId = isset($_GET['companyId'])?$_GET['companyId']:null;
         //前端传来的userId
         $userId = isset($_GET['userId'])?$_GET['userId']:null;
         $id = isset($_GET['id'])?$_GET['id']:null;
         if(empty($companyId) || is_null($companyId)){
             $json->response(404,"没有companyId","");
         }
         if(empty($userId)|| is_null($userId)){
             $json->response(404,"$userId","");
         }
         $ticket_url = "http://auth.bbpaina.com/wechat/oauth.php?wx=aoershi&url=".urlencode("http://ceshi.babypn.com/vote_list.php?action=getVoteId&userId=".$userId."&companyId=".$companyId."&id=".$id);
         header("Location:".$ticket_url);
     }
     public function checkOpenid(){
         if(empty($_SESSION['openid']) || is_null($_SESSION['openid'])){
             echo "OK";
         }
     }
     public function getVoteList(){
        $json = new CreateJson();
        $ticket = $_GET['access_ticket'];
        $user_id = isset($_GET['userId'])?$_GET['userId']:null;
        $companyId = isset($_GET['companyId'])?$_GET['companyId']:null;
        $id = isset($_GET['id'])?$_GET['id']:null;
        if(is_null($user_id) || empty($user_id)){
             $json->response(404,"userId为空","");
         }
        if(empty($companyId) || is_null($companyId)){
             $json->response(404,"没有companyId","");
         }
        $openid = null;
        $res = file_get_contents('http://auth.bbpaina.com/wechat/get.php?ver=0.1&ticket=' . $ticket);
        $openidJson = json_decode($res, true);
        if ($openidJson['status'] == 'ok') {
             //$openid = $openidJson['result']['open_id'];
             $_SESSION['openid'] = $openidJson['result']['open_id'];
             //$_SESSION['access_token'] = $openidJson['result']['access_token'];
        }
        if($id == 1){
            $voteDetailUrl = "http://ceshi.babypn.com/ticket/votenew.html?userId=". $user_id ."&companyId=".$companyId;
            header("Location:".$voteDetailUrl);
        }else{
            $voteUrl = "http://ceshi.babypn.com/ticket/vote.html?userId=". $user_id ."&companyId=".$companyId;
            header("Location:".$voteUrl);
        }
     }
     public function getLists(){
         $json = new CreateJson();
         //$pdoMySQL = new PdoMySQL();
         $user_id = isset($_GET['userId'])?$_GET['userId']:null;
         $companyId = isset($_GET['companyId'])?$_GET['companyId']:null;
         if(empty($user_id) || is_null($user_id)){
             $json->response(404,"没有userId","");
         }
         if(empty($companyId) || is_null($companyId)){
             $json->response(404,"没有companyId","");
         }
         $user_table = 'vote_company';
         $sql = "SELECT `id`,`user_name`,`user_img`,`user_title`,`user_openid`,`vote_num` FROM ${user_table} WHERE active_id = '" . $companyId ."' AND id = '". $user_id . "' AND status = 1";
         $stmt = $GLOBALS['PDO']->prepare($sql);
         $stmt->execute();
         $result = $stmt->fetch();
         //$result = $pdoMySQL::find($user_table,"active_id='". $companyId ."' AND id = '". $user_id ."' AND status = 1","id,user_name,user_img,user_title,user_openid");
         if($result){
             $user_openid = $result['user_openid'];
             $_SESSION['user_openid'] = $user_openid;
             if($result['user_openid'] == $_SESSION['openid']){
                 //已经上传玩过了
                 $list = array(
                     "status" => 1
                 );
                 $arr = array_merge($result,$list);
                 $json->response(200,"自己进自己的页面",$arr);
             }else{
                 //没有玩过
                 $list = array(
                     "status" => 0
                 );
                 $arr = array_merge($result,$list);
                 $json->response(200,"没有玩过哦",$arr);
             }
         }else{
             //数组为空
             $json->response(500,"数组为空","");
         }
     }
     public function thumbUP(){
        $json = new CreateJson();
        $table_thumb = "vote_thumb_up";
        $table_user = "vote_company";
        $userId = isset($_GET['userId'])?$_GET['userId']:null;
        $companyId = isset($_GET['companyId'])?$_GET['companyId']:null;
        if(is_null($userId) || empty($userId)){
            $json->response(404,"userId为空","");
        }
         if(empty($companyId) || is_null($companyId)){
             $json->response(404,"没有companyId","");
        }
        //$openid = "ouKd3jmJdQbJjOa0rJ4DB4suhEDk";
        //$openid = "ouKd3jmJdQbJjOa0rJ4DB4suhEDk";
        if(is_null($_SESSION['openid']) || empty($_SESSION['openid']) ){
            $json->response(404,"openid为空","");
        }
         //$pdoMySQL = new PdoMySQL();
        $sql = "SELECT is_thumb FROM ".$table_thumb." WHERE user_id = '".$userId."' AND openId ='".$_SESSION['openid']."'AND active_id = ".$companyId;
        $stmt = $GLOBALS['PDO']->prepare($sql);
        $stmt->execute();
        $is_thumb = $stmt->fetch();
        $countSql = "SELECT COUNT(openId) num FROM ".$table_thumb." WHERE is_thumb = 1 AND openId ='".$_SESSION['openid']."' AND active_id=".$companyId." AND DATE_FORMAT(thumb_time,'%Y-%M-%d') = DATE_FORMAT(sysdate(),'%Y-%M-%d')";
        $stmp = $GLOBALS['PDO']->prepare($countSql);
        $stmp->execute();
        $count_num = $stmp->fetch();
         if($count_num['num'] >= VOTE_NUM){
             $json->response(300,"今天你不能再投票了哦!","");
         }
         if($is_thumb['is_thumb'] == 1){
             $json->response(300,"今天您已经投过给他了","");
         }else{
             $arr = array(
                 ":userid" => $userId,
                 ":openId"  => $_SESSION['openid'],
                 ":isthumb"=> 1,
                 ":activeid" => $companyId,
             );
             try{
                 $GLOBALS['PDO']->beginTransaction();
                 $insertSql = "INSERT INTO ".$table_thumb."(`user_id`,`openId`,`is_thumb`,`active_id`) VALUES(:userid,:openId,:isthumb,:activeid)";
                 $updateSql = " UPDATE ".$table_user." SET vote_num=vote_num+1 WHERE id=". $userId ." AND active_id=". $companyId;
                 $stmt = $GLOBALS['PDO']->prepare($insertSql);
                 $st = $GLOBALS['PDO']->prepare($updateSql);
                 $resInsert = $stmt->execute($arr);
                 $resUpdate = $st->execute();
                 $GLOBALS['PDO']->commit();
             }catch(Exception $e){
                 $GLOBALS['PDO']->rollBack();
                 $json->response(404,"Failed: " . $e->getMessage(),"");
             }
             if($resInsert && $resUpdate){
                 $json->response(200,"投票成功","");
             }else{
                 $json->response(404,"投票失败","");
             }
         }
     }
     public function getListPage(){
         //$pdoMySQL = new PdoMySQL();
         $json = new CreateJson();
         $user_id = isset($_GET['userId'])?$_GET['userId']:null;
         $companyId = isset($_GET['companyId'])?$_GET['companyId']:null;
         if(empty($user_id) || is_null($user_id)){
             $json->response(404,"没有userId","");
         }
         if(empty($companyId) || is_null($companyId)){
             $json->response(404,"没有companyId","");
         }
         $page = isset($_GET["page"])?intval($_GET["page"]):1;
         //一次默认10条
         $pageSize = isset($_GET["pageSize"])?intval($_GET["pageSize"]):10;
         //$openid = $_SESSION['user_openid'];
         //$openid = "1234";
         $sql = "SELECT `id` FROM vote_company WHERE id != '{$user_id}' AND status = '1' AND active_id = " . $companyId;
         //$result = $pdoMySQL::getAll($sql);
         $stmt = $GLOBALS['PDO']->prepare($sql);
         $stmt->execute();
         $result = $stmt->fetchAll();
         if(empty($result)){
             $json->response(400,"数据请求回来数组为空","");
         }
         $rows = count($result);
         $totalPage = ceil($rows/$pageSize);
         if($page<=1){
             $page = 1;
         }
         if($page>$totalPage){
             $page = $totalPage;
         }
         $startPage = ($page-1)*$pageSize; //开始的条数
         $sqlPage = "SELECT `id`,`user_img`,`user_title`,`baby_name`,`vote_num`,`active_id` FROM vote_company WHERE id != '{$user_id}' AND status = '1' AND active_id = '" . $companyId ."' order by id asc limit ${startPage},${pageSize}";
         $result = $GLOBALS['PDO']->prepare($sqlPage);
         $result->execute();
         $page_result=$result->fetchAll(PDO::FETCH_ASSOC);
         //$page_result = $pdoMySQL::getAll($sqlPage);
         if(!empty($page_result)){
             $pageArr = array(
                 "code"       => 200,
                 "totalPage"  => $totalPage,
                 "lists"      => $page_result,
             );
             echo json_encode($pageArr);
             exit;
         }else{
             $json->response(300,"没有更多数据了","");
         }
     }
     public function clickVotePic(){
         $json = new CreateJson();
         $userId = isset($_GET['userId'])?$_GET['userId']:null;
         $companyId = isset($_GET['companyId'])?$_GET['companyId']:null;
         if(is_null($userId) || empty($userId)){
             $json->response(404,"userId为空","");
         }
         if(empty($companyId) || is_null($companyId)){
             $json->response(404,"没有companyId","");
         }
         $sql = "SELECT `id`,`user_img`,`user_title`,`baby_name`,`vote_num` FROM vote_company WHERE id = ".$userId." AND active_id = ".$companyId." AND status = 1";
         $stmt = $GLOBALS['PDO']->prepare($sql);
         $stmt->execute();
         $result = $stmt->fetch(PDO::FETCH_ASSOC);
         if(empty($result)){
             $json->response(404,"没有数据","");
         }
         $json->response(200,"成功",$result);
     }
 }